#import "DlnaPlayer.h"
#import <React/RCTConvert.h>
#import <MediaPlayer/MediaPlayer.h>
#import <Network/Network.h>

@interface DlnaPlayer ()

// AirPlay相关属性
@property (nonatomic, strong) AVRouteDetector *routeDetector;
@property (nonatomic, strong) NSArray<AVRouteDescription *> *airplayRoutes;
@property (nonatomic, strong) AVRouteDescription *currentRoute;
@property (nonatomic, strong) AVPlayer *player;
@property (nonatomic, strong) AVPlayerItem *playerItem;
@property (nonatomic, strong) id timeObserver;

@end

@implementation DlnaPlayer

RCT_EXPORT_MODULE()

- (instancetype)init {
    self = [super init];
    if (self) {
        // 初始化AirPlay路由检测器
        _routeDetector = [[AVRouteDetector alloc] init];
        _routeDetector.routeDetectionEnabled = YES;
        
        // 使用弱引用避免循环引用
        __weak typeof(self) weakSelf = self;
        
        // 监听AirPlay路由变化
        [[NSNotificationCenter defaultCenter] addObserver:weakSelf
                                                 selector:@selector(handleRouteChange:)
                                                     name:AVRouteDetectorMultipleRoutesDetectedDidChangeNotification
                                                   object:_routeDetector];
    }
    return self;
}

- (void)dealloc {
    // 移除通知监听
    [[NSNotificationCenter defaultCenter] removeObserver:self];
    
    // 移除时间观察者
    if (_timeObserver && _player) {
        [_player removeTimeObserver:_timeObserver];
        _timeObserver = nil;
    }
    
    // 停止播放
    [_player pause];
    _player = nil;
    _playerItem = nil;
}

#pragma mark - 通知处理

- (void)handleRouteChange:(NSNotification *)notification {
    // 更新可用的AirPlay路由
    [self updateAirplayRoutes];
}

#pragma mark - 私有方法

- (void)updateAirplayRoutes {
    // 获取当前可用的AirPlay路由
    MPRouteDescription *currentRoute = [MPMusicPlayerController systemMusicPlayer].nowPlayingItem.playbackRoute;
    NSArray<MPRouteDescription *> *availableRoutes = [MPMusicPlayerController systemMusicPlayer].availableRoutes;
    
    NSMutableArray *airplayRoutes = [NSMutableArray array];
    
    for (MPRouteDescription *route in availableRoutes) {
        if ([route.routeType isEqualToString:MPRouteTypeAirPlay]) {
            [airplayRoutes addObject:route];
        }
    }
    
    self.airplayRoutes = airplayRoutes;
    
    // 更新当前路由
    if (currentRoute && [currentRoute.routeType isEqualToString:MPRouteTypeAirPlay]) {
        for (AVRouteDescription *route in self.airplayRoutes) {
            if ([route.routeID isEqualToString:currentRoute.routeID]) {
                self.currentRoute = route;
                break;
            }
        }
    } else {
        self.currentRoute = nil;
    }
}

#pragma mark - 导出方法

/**
 * 搜索设备
 */
RCT_EXPORT_METHOD(searchDevices:(RCTPromiseResolveBlock)resolve
                  reject:(RCTPromiseRejectBlock)reject) {
    // 更新AirPlay路由
    [self updateAirplayRoutes];
    
    // 构建设备列表
    NSMutableArray *devices = [NSMutableArray array];
    
    for (MPRouteDescription *route in self.airplayRoutes) {
        NSMutableDictionary *device = [NSMutableDictionary dictionary];
        device[@"id"] = route.routeID;
        device[@"name"] = route.routeName;
        device[@"ipAddress"] = @""; // AirPlay不提供IP地址
        device[@"type"] = @"airplay";
        
        [devices addObject:device];
    }
    
    resolve(devices);
}

/**
 * 连接设备
 */
RCT_EXPORT_METHOD(connectToDevice:(NSString *)deviceId
                  resolve:(RCTPromiseResolveBlock)resolve
                  reject:(RCTPromiseRejectBlock)reject) {
    // 空值检查
    if (!deviceId || [deviceId length] == 0) {
        reject(@"CONNECT_ERROR", @"设备ID不能为空", nil);
        return;
    }
    
    // 确保已经加载了设备列表
    if (self.airplayRoutes.count == 0) {
        [self updateAirplayRoutes];
    }
    
    // 查找设备
    MPRouteDescription *targetRoute = nil;
    
    for (MPRouteDescription *route in self.airplayRoutes) {
        if ([route.routeID isEqualToString:deviceId]) {
            targetRoute = route;
            break;
        }
    }
    
    if (!targetRoute) {
        // 提供更详细的错误信息
        NSString *errorMessage = [NSString stringWithFormat:@"设备未找到 (ID: %@)，可用设备数量: %lu", deviceId, (unsigned long)self.airplayRoutes.count];
        reject(@"CONNECT_ERROR", errorMessage, nil);
        return;
    }
    
    // 尝试连接设备
    @try {
        [[MPMusicPlayerController systemMusicPlayer] setPlaybackRoute:targetRoute];
        self.currentRoute = targetRoute;
        resolve(@YES);
    } @catch (NSException *exception) {
        // 捕获可能的异常
        NSString *errorMessage = [NSString stringWithFormat:@"连接设备失败: %@", exception.reason];
        reject(@"CONNECT_ERROR", errorMessage, nil);
    } @finally {
        // 记录连接尝试日志
        NSLog(@"尝试连接设备: %@", targetRoute.routeName);
    }
}

/**
 * 断开设备连接
 */
RCT_EXPORT_METHOD(disconnectFromDevice:(RCTPromiseResolveBlock)resolve
                  reject:(RCTPromiseRejectBlock)reject) {
    if (!self.currentRoute) {
        resolve(@YES);
        return;
    }
    
    // 断开连接
    [[MPMusicPlayerController systemMusicPlayer] setPlaybackRoute:nil];
    self.currentRoute = nil;
    
    // 停止播放
    if (self.player) {
        [self.player pause];
        self.player = nil;
        self.playerItem = nil;
    }
    
    resolve(@YES);
}

/**
 * 清理播放资源
 * 在播放新视频前或模块销毁时调用，防止资源泄漏
 */
- (void)cleanupPlaybackResources {
    // 在主线程执行清理操作
    if (![NSThread isMainThread]) {
        dispatch_async(dispatch_get_main_queue(), ^{
            [self cleanupPlaybackResources];
        });
        return;
    }
    
    // 移除时间观察者
    if (_timeObserver && _player) {
        [_player removeTimeObserver:_timeObserver];
        _timeObserver = nil;
    }
    
    // 移除通知监听
    if (_playerItem) {
        [[NSNotificationCenter defaultCenter] removeObserver:self 
                                                        name:AVPlayerItemDidPlayToEndTimeNotification 
                                                      object:_playerItem];
        [[NSNotificationCenter defaultCenter] removeObserver:self 
                                                        name:AVPlayerItemFailedToPlayToEndTimeNotification 
                                                      object:_playerItem];
        [[NSNotificationCenter defaultCenter] removeObserver:self 
                                                        name:AVPlayerItemPlaybackStalledNotification 
                                                      object:_playerItem];
    }
    
    // 暂停播放器
    if (_player) {
        [_player pause];
        [_player replaceCurrentItemWithPlayerItem:nil];
    }
    
    // 释放资源
    _playerItem = nil;
    _player = nil;
    
    NSLog(@"播放资源已清理");
}

/**
 * 模块销毁时调用
 */
- (void)invalidate {
    // 清理播放资源
    [self cleanupPlaybackResources];
    
    // 移除路由变化通知监听
    [[NSNotificationCenter defaultCenter] removeObserver:self];
    
    // 禁用路由检测
    if (_routeDetector) {
        _routeDetector.routeDetectionEnabled = NO;
        _routeDetector = nil;
    }
    
    // 清空路由列表
    _airplayRoutes = nil;
    _currentRoute = nil;
    
    NSLog(@"DlnaPlayer模块已销毁");
}

/**
 * 播放视频
 */
RCT_EXPORT_METHOD(playVideo:(NSString *)url
                  title:(NSString *)title
                  subtitle:(NSString *)subtitle
                  coverUrl:(NSString *)coverUrl
                  resolver:(RCTPromiseResolveBlock)resolve
                  rejecter:(RCTPromiseRejectBlock)reject)
{
    // 首先清理之前的播放资源
    [self cleanupPlaybackResources];
    
    // 在主线程执行播放操作
    dispatch_async(dispatch_get_main_queue(), ^{
        @try {
            // 检查URL是否有效
            NSURL *videoURL = [NSURL URLWithString:url];
            if (!videoURL) {
                reject(@"INVALID_URL", @"无效的视频URL", nil);
                return;
            }
            
            // 检查是否有可用的AirPlay设备
            if (!self.currentRoute) {
                reject(@"NO_DEVICE_CONNECTED", @"未连接到AirPlay设备", nil);
                return;
            }
            
            // 创建AVPlayerItem
            AVPlayerItem *playerItem = [AVPlayerItem playerItemWithURL:videoURL];
            
            // 创建AVPlayer
            if (!self.player) {
                self.player = [AVPlayer playerWithPlayerItem:playerItem];
            } else {
                [self.player replaceCurrentItemWithPlayerItem:playerItem];
            }
            
            self.playerItem = playerItem;
            
            // 设置元数据
            if (title) {
                // 设置视频标题等元数据
                // ...
            }
            
            // 添加播放完成通知
            [[NSNotificationCenter defaultCenter] addObserver:self
                                                     selector:@selector(playerItemDidReachEnd:)
                                                         name:AVPlayerItemDidPlayToEndTimeNotification
                                                       object:playerItem];
            
            // 添加播放失败通知
            [[NSNotificationCenter defaultCenter] addObserver:self
                                                     selector:@selector(playerItemFailedToPlayToEnd:)
                                                         name:AVPlayerItemFailedToPlayToEndTimeNotification
                                                       object:playerItem];
            
            // 添加播放卡顿通知
            [[NSNotificationCenter defaultCenter] addObserver:self
                                                     selector:@selector(playerItemPlaybackStalled:)
                                                         name:AVPlayerItemPlaybackStalledNotification
                                                       object:playerItem];
            
            // 添加时间观察者
            __weak typeof(self) weakSelf = self;
            self.timeObserver = [self.player addPeriodicTimeObserverForInterval:CMTimeMakeWithSeconds(1.0, NSEC_PER_SEC)
                                                                          queue:dispatch_get_main_queue()
                                                                     usingBlock:^(CMTime time) {
                [weakSelf updatePlaybackStatus];
            }];
            
            // 开始播放
            [self.player play];
            
            // 启用AirPlay
            [[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayback error:nil];
            [[AVAudioSession sharedInstance] setActive:YES error:nil];
            
            // 发送播放状态变更事件
            [self updatePlaybackStatus];
            
            resolve(@YES);
        } @catch (NSException *exception) {
            NSError *error = [NSError errorWithDomain:@"DlnaPlayerErrorDomain"
                                                 code:100
                                             userInfo:@{NSLocalizedDescriptionKey: exception.reason ?: @"播放视频时发生错误"}];
            reject(@"PLAYBACK_ERROR", exception.reason ?: @"播放视频时发生错误", error);
        }
    });
}

/**
 * 暂停播放
 */
RCT_EXPORT_METHOD(pauseVideo:(RCTPromiseResolveBlock)resolve
                  reject:(RCTPromiseRejectBlock)reject) {
    if (!self.player) {
        reject(@"PAUSE_ERROR", @"未播放视频", nil);
        return;
    }
    
    [self.player pause];
    [self updatePlaybackInfo];
    
    resolve(@YES);
}

/**
 * 恢复播放
 */
RCT_EXPORT_METHOD(resumeVideo:(RCTPromiseResolveBlock)resolve
                  reject:(RCTPromiseRejectBlock)reject) {
    if (!self.player) {
        reject(@"RESUME_ERROR", @"未播放视频", nil);
        return;
    }
    
    [self.player play];
    [self updatePlaybackInfo];
    
    resolve(@YES);
}

/**
 * 停止播放
 */
RCT_EXPORT_METHOD(stopVideo:(RCTPromiseResolveBlock)resolve
                  reject:(RCTPromiseRejectBlock)reject) {
    if (!self.player) {
        reject(@"STOP_ERROR", @"未播放视频", nil);
        return;
    }
    
    [self.player pause];
    [self.player seekToTime:kCMTimeZero];
    [self updatePlaybackInfo];
    
    resolve(@YES);
}

/**
 * 跳转到指定位置
 */
RCT_EXPORT_METHOD(seekTo:(double)position
                  resolve:(RCTPromiseResolveBlock)resolve
                  reject:(RCTPromiseRejectBlock)reject) {
    if (!self.player) {
        reject(@"SEEK_ERROR", @"未播放视频", nil);
        return;
    }
    
    CMTime time = CMTimeMakeWithSeconds(position, NSEC_PER_SEC);
    [self.player seekToTime:time toleranceBefore:kCMTimeZero toleranceAfter:kCMTimeZero];
    [self updatePlaybackInfo];
    
    resolve(@YES);
}

/**
 * 获取播放状态
 */
RCT_EXPORT_METHOD(getPlaybackStatus:(RCTPromiseResolveBlock)resolve
                  reject:(RCTPromiseRejectBlock)reject) {
    NSMutableDictionary *status = [NSMutableDictionary dictionary];
    
    if (!self.player || !self.playerItem) {
        status[@"isPlaying"] = @NO;
        status[@"position"] = @0;
        status[@"duration"] = @0;
        status[@"isBuffering"] = @NO;
        status[@"isCompleted"] = @NO;
        status[@"isError"] = @NO;
        
        resolve(status);
        return;
    }
    
    // 播放状态
    status[@"isPlaying"] = @(self.player.rate > 0);
    
    // 播放位置
    CMTime currentTime = self.player.currentTime;
    status[@"position"] = @(CMTimeGetSeconds(currentTime));
    
    // 视频时长
    CMTime duration = self.playerItem.duration;
    status[@"duration"] = @(CMTimeGetSeconds(duration));
    
    // 缓冲状态
    status[@"isBuffering"] = @(self.playerItem.isPlaybackBufferEmpty);
    
    // 是否播放完成
    status[@"isCompleted"] = @(self.playerItem.status == AVPlayerItemStatusReadyToPlay && CMTimeGetSeconds(currentTime) >= CMTimeGetSeconds(duration));
    
    // 错误状态
    status[@"isError"] = @(self.playerItem.status == AVPlayerItemStatusFailed);
    if (self.playerItem.status == AVPlayerItemStatusFailed && self.playerItem.error) {
        status[@"errorMessage"] = [self.playerItem.error localizedDescription];
    }
    
    resolve(status);
}

/**
 * 设置音量
 */
RCT_EXPORT_METHOD(setVolume:(double)volume
                  resolve:(RCTPromiseResolveBlock)resolve
                  reject:(RCTPromiseRejectBlock)reject) {
    if (!self.player) {
        reject(@"VOLUME_ERROR", @"未播放视频", nil);
        return;
    }
    
    // 将0-100的音量转换为0-1
    float normalizedVolume = (float)volume / 100.0f;
    [MPMusicPlayerController systemMusicPlayer].volume = normalizedVolume;
    
    resolve(@YES);
}

/**
 * 获取音量
 */
RCT_EXPORT_METHOD(getVolume:(RCTPromiseResolveBlock)resolve
                  reject:(RCTPromiseRejectBlock)reject) {
    // 将0-1的音量转换为0-100
    float volume = [MPMusicPlayerController systemMusicPlayer].volume * 100.0f;
    resolve(@(volume));
}

/**
 * 设置静音
 */
RCT_EXPORT_METHOD(setMute:(BOOL)mute
                  resolve:(RCTPromiseResolveBlock)resolve
                  reject:(RCTPromiseRejectBlock)reject) {
    if (!self.player) {
        reject(@"MUTE_ERROR", @"未播放视频", nil);
        return;
    }
    
    self.player.muted = mute;
    resolve(@YES);
}

/**
 * 获取静音状态
 */
RCT_EXPORT_METHOD(getMute:(RCTPromiseResolveBlock)resolve
                  reject:(RCTPromiseRejectBlock)reject) {
    if (!self.player) {
        reject(@"MUTE_ERROR", @"未播放视频", nil);
        return;
    }
    
    resolve(@(self.player.muted));
}

#pragma mark - 权限管理

/**
 * 检查权限
 */
RCT_EXPORT_METHOD(checkPermissions:(RCTPromiseResolveBlock)resolve
                  reject:(RCTPromiseRejectBlock)reject)
{
    NSMutableDictionary *result = [NSMutableDictionary dictionary];
    NSMutableArray *missingPermissions = [NSMutableArray array];
    BOOL hasAllPermissions = YES;
    
    // iOS 14+需要本地网络权限
    if (@available(iOS 14, *)) {
        // 检查Info.plist是否包含NSLocalNetworkUsageDescription
        NSString *localNetworkUsageDescription = [[NSBundle mainBundle] objectForInfoDictionaryKey:@"NSLocalNetworkUsageDescription"];
        if (!localNetworkUsageDescription) {
            hasAllPermissions = NO;
            [missingPermissions addObject:@"NSLocalNetworkUsageDescription"];
            NSLog(@"警告: Info.plist中缺少NSLocalNetworkUsageDescription");
        }
        
        // 检查Info.plist是否包含NSBonjourServices
        NSArray *bonjourServices = [[NSBundle mainBundle] objectForInfoDictionaryKey:@"NSBonjourServices"];
        if (!bonjourServices || ![bonjourServices containsObject:@"_googlecast._tcp"]) {
            hasAllPermissions = NO;
            [missingPermissions addObject:@"NSBonjourServices"];
            NSLog(@"警告: Info.plist中缺少NSBonjourServices或未包含_googlecast._tcp");
        }
    }
    
    result[@"hasPermissions"] = @(hasAllPermissions);
    
    if (!hasAllPermissions) {
        result[@"missingPermissions"] = missingPermissions;
    }
    
    resolve(result);
}

/**
 * 检查本地网络权限
 */
RCT_EXPORT_METHOD(checkLocalNetworkPermission:(RCTPromiseResolveBlock)resolve
                  reject:(RCTPromiseRejectBlock)reject)
{
    if (@available(iOS 14, *)) {
        // 创建一个临时的本地网络浏览器来检测权限
        dispatch_async(dispatch_get_main_queue(), ^{
            // 使用Network框架检查本地网络权限
            nw_browser_t browser = nw_browser_create();
            
            // 设置一个标志来跟踪是否已经解决了Promise
            __block BOOL promiseResolved = NO;
            
            // 设置状态变更处理程序
            nw_browser_set_state_changed_handler(browser, ^(nw_browser_state_t state, nw_error_t error) {
                if (!promiseResolved) {
                    if (state == nw_browser_state_ready) {
                        // 浏览器准备就绪，表示有权限
                        promiseResolved = YES;
                        nw_browser_cancel(browser);
                        resolve(@YES);
                    } else if (state == nw_browser_state_failed && error) {
                        // 浏览器失败，可能是权限问题
                        promiseResolved = YES;
                        nw_browser_cancel(browser);
                        resolve(@NO);
                    }
                }
            });
            
            // 启动浏览器
            nw_browser_start(browser);
            
            // 设置超时
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 2 * NSEC_PER_SEC), dispatch_get_main_queue(), ^{
                if (!promiseResolved) {
                    promiseResolved = YES;
                    nw_browser_cancel(browser);
                    // 超时，假设有权限
                    resolve(@YES);
                }
            });
        });
    } else {
        // iOS 14以下不需要特殊权限
        resolve(@YES);
    }
}

/**
 * 提示用户授予本地网络权限
 */
RCT_EXPORT_METHOD(promptForLocalNetworkPermission:(NSDictionary *)options
                  resolve:(RCTPromiseResolveBlock)resolve
                  reject:(RCTPromiseRejectBlock)reject)
{
    dispatch_async(dispatch_get_main_queue(), ^{
        NSString *title = options[@"title"] ?: @"需要本地网络权限";
        NSString *message = options[@"message"] ?: @"请在系统设置中允许应用访问本地网络，以便发现并连接到DLNA设备。";
        
        UIAlertController *alert = [UIAlertController
                                   alertControllerWithTitle:title
                                   message:message
                                   preferredStyle:UIAlertControllerStyleAlert];
        
        [alert addAction:[UIAlertAction
                         actionWithTitle:@"去设置"
                         style:UIAlertActionStyleDefault
                         handler:^(UIAlertAction * _Nonnull action) {
            // 跳转到应用设置
            NSURL *settingsURL = [NSURL URLWithString:UIApplicationOpenSettingsURLString];
            if ([[UIApplication sharedApplication] canOpenURL:settingsURL]) {
                [[UIApplication sharedApplication] openURL:settingsURL options:@{} completionHandler:nil];
            }
            resolve(@YES);
        }]];
        
        [alert addAction:[UIAlertAction
                         actionWithTitle:@"取消"
                         style:UIAlertActionStyleCancel
                         handler:^(UIAlertAction * _Nonnull action) {
            resolve(@NO);
        }]];
        
        UIViewController *rootVC = RCTPresentedViewController();
        [rootVC presentViewController:alert animated:YES completion:nil];
    });
}

/**
 * 显示权限请求理由
 */
RCT_EXPORT_METHOD(showPermissionRationale:(NSString *)permissionName
                  rationale:(NSString *)rationale
                  resolve:(RCTPromiseResolveBlock)resolve
                  reject:(RCTPromiseRejectBlock)reject)
{
    dispatch_async(dispatch_get_main_queue(), ^{
        UIAlertController *alert = [UIAlertController
                                   alertControllerWithTitle:[NSString stringWithFormat:@"需要%@权限", permissionName]
                                   message:rationale
                                   preferredStyle:UIAlertControllerStyleAlert];
        
        [alert addAction:[UIAlertAction
                         actionWithTitle:@"确定"
                         style:UIAlertActionStyleDefault
                         handler:^(UIAlertAction * _Nonnull action) {
            resolve(@YES);
        }]];
        
        UIViewController *rootVC = RCTPresentedViewController();
        [rootVC presentViewController:alert animated:YES completion:nil];
    });
}

#pragma mark - 错误处理

/**
 * 创建标准化错误对象
 */
- (NSDictionary *)createErrorWithCode:(NSString *)code message:(NSString *)message details:(NSDictionary *)details {
    NSMutableDictionary *error = [NSMutableDictionary dictionary];
    
    error[@"code"] = code;
    error[@"message"] = message;
    
    if (details) {
        error[@"details"] = details;
    }
    
    return error;
}

/**
 * 创建NSError对象
 */
- (NSError *)createNSErrorWithCode:(NSString *)code message:(NSString *)message details:(NSDictionary *)details {
    NSMutableDictionary *userInfo = [NSMutableDictionary dictionary];
    
    userInfo[NSLocalizedDescriptionKey] = message;
    
    if (details) {
        userInfo[@"details"] = details;
    }
    
    return [NSError errorWithDomain:@"DlnaPlayerErrorDomain" 
                               code:[self errorCodeToInt:code] 
                           userInfo:userInfo];
}

/**
 * 将错误代码转换为整数
 */
- (NSInteger)errorCodeToInt:(NSString *)code {
    // 为每个错误代码分配一个唯一的整数值
    static NSDictionary *errorCodes;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        errorCodes = @{
            @"UNKNOWN_ERROR": @100,
            @"NETWORK_ERROR": @101,
            @"DEVICE_NOT_FOUND": @102,
            @"CONNECTION_FAILED": @103,
            @"DISCONNECTION_FAILED": @104,
            @"PLAYBACK_FAILED": @105,
            @"PAUSE_FAILED": @106,
            @"RESUME_FAILED": @107,
            @"STOP_FAILED": @108,
            @"SEEK_FAILED": @109,
            @"GET_STATUS_FAILED": @110,
            @"VOLUME_CONTROL_FAILED": @111,
            @"INVALID_PARAMETER": @112,
            @"METHOD_NOT_IMPLEMENTED": @113,
            @"PERMISSION_ERROR": @114,
            @"PERMISSION_PERMANENTLY_DENIED": @115,
            @"DEVICE_NOT_SUPPORTED": @116,
            @"ALREADY_CONNECTING": @117
        };
    });
    
    NSNumber *codeNumber = errorCodes[code];
    return codeNumber ? [codeNumber integerValue] : 100; // 默认为UNKNOWN_ERROR
}

/**
 * 发送错误事件
 */
- (void)sendErrorEventWithCode:(NSString *)code message:(NSString *)message details:(NSDictionary *)details {
    NSDictionary *error = [self createErrorWithCode:code message:message details:details];
    [self sendEventWithName:@"errorOccurred" body:error];
}

/**
 * 拒绝Promise并发送错误事件
 */
- (void)rejectPromise:(RCTPromiseRejectBlock)reject 
             withCode:(NSString *)code 
              message:(NSString *)message 
              details:(NSDictionary *)details {
    // 创建NSError对象
    NSError *error = [self createNSErrorWithCode:code message:message details:details];
    
    // 发送错误事件
    [self sendErrorEventWithCode:code message:message details:details];
    
    // 拒绝Promise
    reject(code, message, error);
}

/**
 * 将NSError转换为标准化错误对象
 */
- (NSDictionary *)convertNSErrorToStandardError:(NSError *)error defaultCode:(NSString *)defaultCode {
    NSString *code = defaultCode;
    NSString *message = error.localizedDescription;
    
    NSMutableDictionary *details = [NSMutableDictionary dictionary];
    
    // 添加错误域
    details[@"domain"] = error.domain;
    
    // 添加错误代码
    details[@"nativeCode"] = @(error.code);
    
    // 添加用户信息
    if (error.userInfo) {
        details[@"userInfo"] = error.userInfo;
    }
    
    return [self createErrorWithCode:code message:message details:details];
}

#pragma mark - 辅助方法

/**
 * 更新播放信息
 */
- (void)updatePlaybackInfo {
    if (!self.player || !self.playerItem) {
        return;
    }
    
    NSMutableDictionary *playbackInfo = [NSMutableDictionary dictionary];
    
    if ([MPNowPlayingInfoCenter defaultCenter].nowPlayingInfo) {
        [playbackInfo addEntriesFromDictionary:[MPNowPlayingInfoCenter defaultCenter].nowPlayingInfo];
    }
    
    // 更新播放位置和时长
    playbackInfo[MPNowPlayingInfoPropertyElapsedPlaybackTime] = @(CMTimeGetSeconds(self.player.currentTime));
    playbackInfo[MPMediaItemPropertyPlaybackDuration] = @(CMTimeGetSeconds(self.playerItem.duration));
    playbackInfo[MPNowPlayingInfoPropertyPlaybackRate] = @(self.player.rate);
    
    [MPNowPlayingInfoCenter defaultCenter].nowPlayingInfo = playbackInfo;
}

@end 